const path = require("path");
const webpack = require('webpack')
const ThemeColorReplacer = require('webpack-theme-color-replacer')
const { getThemeColors, modifyVars } = require('./src/utils/themeUtil')
const { resolveCss } = require('./src/utils/theme-color-replacer-extend')
const CompressionWebpackPlugin = require('compression-webpack-plugin')

const productionGzipExtensions = ['js', 'css']
const isProd = process.env.NODE_ENV === 'production'
let vars = path.resolve(__dirname, 'src/theme/index.less')  

const assetsCDN = {
  // webpack build externals
  externals: {
    //vue: 'Vue',
    //mockjs: 'mockjs',
    'vue-i18n': 'VueI18n',
    //'vue-router': 'VueRouter',
    vuex: 'Vuex',
    //'v-charts': 'VeChart',
    // axios: 'axios',
    nprogress: 'NProgress',
    clipboard: 'ClipboardJS',
    //'@antv/data-set': 'DataSet',
    //'js-cookie': 'Cookies',
    lodash: '_',
    "moment": "moment",
    "../moment": "moment",
    //"@antv/g2": "G2",
    //'object-assign': 'objectAssign',
    'less':'less'
  },
  css: [
  ],
  js: [
    // '//cdn.jsdelivr.net/npm/vue@2.6.11/dist/vue.min.js',
    // '//cdn.jsdelivr.net/npm/vue-router@3.3.4/dist/vue-router.min.js',
    // '//cdn.jsdelivr.net/npm/vuex@3.4.0/dist/vuex.min.js',
    // '//cdn.jsdelivr.net/npm/axios@0.19.2/dist/axios.min.js',
    // '//cdn.jsdelivr.net/npm/nprogress@0.2.0/nprogress.min.js',
    // '//cdn.jsdelivr.net/npm/clipboard@2.0.6/dist/clipboard.min.js',
    // '//cdn.jsdelivr.net/npm/@antv/data-set@0.11.4/build/data-set.min.js',
    // '//cdn.jsdelivr.net/npm/js-cookie@2.2.1/src/js.cookie.min.js'
  ]
}
module.exports = {
  devServer: {
    // proxy: {
    //   '/api': { //此处要与 /services/api.js 中的 API_PROXY_PREFIX 值保持一致
    //     target: process.env.VUE_APP_API_BASE_URL,
    //     changeOrigin: true,
    //     pathRewrite: {
    //       '^/api': ''
    //     }
    //   }
    // }
  },
  css: {
    loaderOptions: {
      less: {
        lessOptions: {
          globalVars: {
            "hack": `true; @import "${vars}"`
          },
          // If you are using less-loader@5 please spread the lessOptions to options directly
          modifyVars: modifyVars(),
          javascriptEnabled: true,
        },
      },
    },
  },
  pluginOptions: {
    'style-resources-loader': {
      preProcessor: 'less',
      patterns: [path.resolve(__dirname, "src/theme/index.less")],
    },
    electronBuilder: {
      nodeIntegration: true,
      builderOptions: {
        productName: "electron-vue-ant",
        appId: "com.electron.app",
        copyright: "Copyright ©2020 Yourwebsite.com",
        electronDownload: {
          mirror: "https://npm.taobao.org/mirrors/electron/"
        },
        directories: {
          output: "build",
        },
        mac: {
          identity: "com.electron.app",
          target: ["dmg"],
          artifactName: "${productName}.${ext}",
          icon: "src/assets/appicon.icns",
        },
        dmg: {
          title: "${productName}",
          artifactName: "${productName}.${ext}",
          icon: "src/assets/appicon.icns",
        },
        win: {
          verifyUpdateCodeSignature: false,
          legalTrademarks: "Copyright ©2020 Yourwebsite.com",
          publisherName: "electron-vue-ant",
          requestedExecutionLevel: "highestAvailable",
          target: [
            {
              target: "nsis",
              arch: ["ia32"],
            },
          ],
          artifactName: "${productName}.${ext}",
          icon: "src/assets/appicon.ico",
        },
        nsis: {
          oneClick: false,
          allowToChangeInstallationDirectory: true,
          perMachine: true,
          allowElevation: true,
          artifactName: "${productName}-V${version}.${ext}",
          runAfterFinish: true,
          shortcutName: "electron-vue-ant",
        },
        publish: [
          {
            provider: "generic",
            url: "http://electron.org/update/",
          },
        ],
      },
    },
  },
  configureWebpack: config => {
    //config.entry.app = ["babel-polyfill", "whatwg-fetch", "./src/main.js"];
    config.performance = {
      hints: false
    }
    config.plugins.push(
      new ThemeColorReplacer({
        fileName: 'css/theme-colors-[contenthash:8].css',
        matchColors: getThemeColors(),
        injectCss: true,
        resolveCss
      })
    )
    // Ignore all locale files of moment.js
    config.plugins.push(new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/))
    // 生产环境下将资源压缩成gzip格式
    // if (isProd) {
    //   // add `CompressionWebpack` plugin to webpack plugins
    //   config.plugins.push(new CompressionWebpackPlugin({
    //     algorithm: 'gzip',
    //     test: new RegExp('\\.(' + productionGzipExtensions.join('|') + ')$'),
    //     threshold: 10240,
    //     minRatio: 0.8
    //   }))
    // }
    // if prod, add externals
    if (isProd) {
      config.externals = assetsCDN.externals
    }
  },
  chainWebpack: config => {
    // config
    //   .plugin("loadshReplace")
    //   .use(new LodashModuleReplacementPlugin());
    // 生产环境下关闭css压缩的 colormin 项，因为此项优化与主题色替换功能冲突
    if (isProd) {
      config.plugin('optimize-css')
        .tap(args => {
          args[0].cssnanoOptions.preset[1].colormin = false
          return args
        })
    }
    // 生产环境下使用CDN
    if (isProd) {
      config.plugin('html')
        .tap(args => {
          args[0].cdn = assetsCDN
          return args
        })
    }
  },
  publicPath: process.env.VUE_APP_PUBLIC_PATH,
  outputDir: 'dist',
  assetsDir: 'static',
  productionSourceMap: false
};
